// https://m.hua.com/ProductList/ListMore?r=0&pIndex=1&kwCode=gifts

let num = 1
const res = []
const fileName = '鲜花网'
const cate = ['to_lover', 'to_friend', 'to_parents', 'to_man', 'to_teacher', 'to_kids']
let index = 0
function fetchData() {
  fetch(`https://m.hua.com/ProductList/ListMore?r=0&pIndex=${num}&kwCode=${cate[index]}`)
    .then(r => r.text())
    .then(r => {
      const dom = createDomByStr(r)
      wash(dom)

      // return
      num++
      if (num <= 10) fetchData()
      else if (index < cate.length) {
        num = 1
        index++
        if (index === cate.length) {
          // console.log('res', res)
          console.log('end----');
          downloadText(`${fileName}.json`, JSON.stringify(res))
        }
        else fetchData()
      }
    })
}

fetchData()

function createDomByStr(domStr) {
  const parser = new DOMParser()
  return parser.parseFromString(domStr, 'text/html').body

}

function wash(dom) {
  const list = dom.querySelectorAll('.product-item')
  list && list.forEach(item => {
    const cateStr = cate[index]
    const link = item.querySelector('.navigation')?.getAttribute('data-link')
    const imgSrc = item.querySelector('.product-item-pic img')?.getAttribute('data-original')
    const name = item.querySelector('.product-item-info-name')?.textContent.trim()
    const tag = item.querySelector('.product-item-info-tags span')?.textContent.trim()
    const price = item.querySelector('.product-item-info-price')?.textContent.match(/(\d+)/)[1]
    const sales = item.querySelector('.product-item-info-sales')?.textContent.match(/(\d+)/)[1]
    res.push({ cateStr, link, imgSrc, name, tag, price, sales })
  })

}

function filter(v) {

}

function downloadText(fileName, text) {
  const url = window.URL || window.webkitURL || window;
  const blob = new Blob([text]);
  const saveLink = document.createElement("a");
  saveLink.href = url.createObjectURL(blob);
  // 设置 download 属性
  saveLink.download = fileName+ '.json';
  saveLink.click();
  url.revokeObjectURL(saveLink.href);
  saveLink?.remove()
}


